package com.qn.visitor.config.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.qn.common.base.model.ResponseCode;
import com.qn.common.base.model.ResponseMode;
import com.qn.core.exception.QnException;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * qingniu-cloud user source analysis
 *
 * @Author: TXG
 * @Date: 2024/6/11
 * @Version V0.0.2
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseMode handleNotFound(HttpServletRequest req, NoHandlerFoundException e) {
        logger.error("NoHandlerFoundException",e);
        return new ResponseMode(ResponseCode.ERROR.code(),"无该资源: " + req.getRequestURI());
    }
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResponseMode arithmeticExceptionHandler(ArithmeticException e){
        logger.error("ArithmeticException",e);
        return new ResponseMode(ResponseCode.ERROR.code(),e.getMessage());
    }
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResponseMode arithmeticExceptionHandler(NotLoginException e){
        logger.error("ArithmeticException",e);
        return new ResponseMode(ResponseCode.UNAUTHORIZED.code(),e.getMessage());
    }
    @ExceptionHandler(QnException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResponseMode exceptionHandler(QnException e){
        logger.error("QnException",e);
        return new ResponseMode(ResponseCode.ERROR.code(), e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResponseMode exceptionHandler(Exception e){
        logger.error("Exception",e);
        return new ResponseMode(ResponseCode.ERROR.code(), e.getLocalizedMessage());
    }
}